package me.ljd.yigo.funext;

import java.net.URLDecoder;

import com.bokesoft.yigo.parser.BaseFunImplCluster;
import com.bokesoft.yigo.parser.IExecutor;
import com.bokesoft.yigo.view.expr.BaseViewFunctionImpl;
import com.bokesoft.yigo.view.expr.ViewEvalContext;
import com.bokesoft.yigo.view.model.IForm;

public class ViewFunctionsExt extends BaseFunImplCluster{
	//截取字符串的最后一部分
	//参数：字符串，分隔符
	class LastPart extends BaseViewFunctionImpl{

		@Override
		public Object evalImpl(String name, ViewEvalContext context, Object[] args, IExecutor executor)
				throws Throwable {
			if(args.length<2 || args[0]==null) {
				return null;
			}
			String str = (String)args[0];
			if(str.length()==0) {return "";}
			return str.substring(str.lastIndexOf((String)args[1])+1);
		}
		
	}
	//按key获取参数字符串中的value
	//参数：参数字符串，key
	class RequsetPara extends BaseViewFunctionImpl{

		@Override
		public Object evalImpl(String name, ViewEvalContext context, Object[] args, IExecutor executor) throws Throwable {
			//System.out.println("name="+name);公式名称
			if(args.length<2 || args[0]==null) {
				return null;
			}
			String content = (String)args[0];
			//content = URLDecoder.decode(content, "UTF-8");
			String[] arrKV = content.split("[&]");
			for(String kv:arrKV)
		    {
		          String[] pair= kv.split("[=]");
		         
		          //解析出键值
		          if(pair.length>1 && pair[0].equals(args[1]))
		          {
		              //正确解析
		              return pair[1];
		             
		          }
		    } 			
			return null;
		}
		
	}
	class HasParent extends BaseViewFunctionImpl{

		@Override
		public Object evalImpl(String name, ViewEvalContext context, Object[] args, IExecutor executor) throws Throwable {
			IForm form = context.getForm(),parentForm = form.getParentForm();
			return parentForm != null ? true : false;
		}
		
	}
	@Override
	public Object[][] getImplTable() {
		System.out.println("ViewFunctionsExt.getImplTable()");
		return new Object[][]{
			{"LastPart", new LastPart()},
			{"RequsetPara",new RequsetPara()},
			{"HasParent",new HasParent()}
		};
	}

}
